<template>
  <div class="">
    <div class="info-title">教练管理</div>
  <el-card class="full-height full-width">
    <search-table class="full-height full-width"
      :table-loading="loading"
      :tableData="tableData"
      :ref="tableRef"
      :labelWidth="'40px'"
      :row-keys="row => row.id"
      @query="currentPage = 1; query();"
      @reset="doReset"
      @selectionChange="selectionChange">
      <template v-slot:row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="名称">
              <el-input placeholder="请输入内容" v-model="searchForm.name" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话">
              <el-input placeholder="请输入内容" v-model="searchForm.tel" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别">
              <el-select placeholder="请选择" v-model="searchForm.sex" clearable>
                <el-option :label="'男'" :value="1"></el-option>
                <el-option :label="'女'" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template v-slot:actions>
        <el-button size="small" type="primary" v-on:click="addCoach()">新 建</el-button>
        <el-button size="small" type="primary" v-on:click="editCoach()">编 辑</el-button>
        <el-button size="small" type="primary" v-on:click="handlerDelete()">删除/批量删除</el-button>
      </template>
      <template >
        <el-table-column :reserve-selection="true" type="selection" width="55" />
        <el-table-column prop="name" label="姓名" width="100" show-overflow-tooltip />
        <el-table-column prop="sex" label="性别" width="50" show-overflow-tooltip />
        <el-table-column prop="tel" label="电话" width="100" show-overflow-tooltip />
        <el-table-column prop="idCard" label="身份证" width="150" show-overflow-tooltip />
        <el-table-column prop="province" label="省份" show-overflow-tooltip />
        <el-table-column prop="unit" label="单位" show-overflow-tooltip />
        <el-table-column prop="state" label="状态" show-overflow-tooltip />
      </template>
      <template v-slot:footer>
        <el-pagination
          background
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </template>
    </search-table>
    <el-dialog  :close-on-click-modal="false" title="修改教练" :visible.sync="dialogFormEdit">
      <el-form id="editsForm"  ref="coach" :model="coach" :rules="rules" label-width="80px" >
        <el-form-item label="教练姓名" prop="name">
          <el-col :span="7">
            <el-input v-model="coach.name" auto-complete="off" ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="教练性别" prop="sex">
          <el-col :span="7">
            <el-select v-model="coach.sex" value-key="id">
              <el-option v-for="item in sexArry"  :key="item.id" :label="item.name" :value="item.name"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="教练电话" prop="tel">
          <el-col :span="7">
            <el-input v-model="coach.tel" auto-complete="off"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="身份证" prop="idCard">
          <el-col :span="12">
            <el-input v-model="coach.idCard" auto-complete="off"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="教练备注" >
          <el-col :span="14">
            <el-input v-model="coach.note" auto-complete="off" type="textarea" :rows="2" />
          </el-col>
        </el-form-item>
        <el-form-item label="所在地区" >
          <el-col :span="7">
            <el-input v-model="coach.province" auto-complete="off" :rows="2" />
            <!-- <el-select v-model="coach.levelId" value-key="id">
              <el-option v-for="item in levelArray"  :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select> -->
          </el-col>
        </el-form-item>
        <el-form-item label="单位" >
          <el-col :span="7">
            <el-input v-model="coach.unit" auto-complete="off" :rows="2" />
          </el-col>
        </el-form-item>
        <el-form-item label="状态" >
          <el-col :span="7">
            <el-select v-model="coach.stateId" value-key="id">
              <el-option v-for="item in stateArray"  :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="edit(coach)">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog  :close-on-click-modal="false" title="添加教练" :visible.sync="dialogFormAdd">
      <el-form id="addsForm"  ref="coach" :model="coach" :rules="rules" label-width="100px" >
        <el-form-item label="教练姓名" prop="name">
          <el-col :span="7">
            <el-input v-model="coach.name" auto-complete="off" ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="教练性别" prop="sex">
          <el-col :span="7">
            <el-select v-model="coach.sex" value-key="id">
              <el-option v-for="item in sexArry"  :key="item.id" :label="item.name" :value="item.name"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="教练电话" prop="tel">
          <el-col :span="7">
            <el-input v-model="coach.tel" auto-complete="off"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="身份证" prop="idCard">
          <el-col :span="12">
            <el-input v-model="coach.idCard" auto-complete="off"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="教练备注" >
          <el-col :span="14">
            <el-input v-model="coach.note" auto-complete="off" type="textarea" :rows="2" />
          </el-col>
        </el-form-item>
        <el-form-item label="所在地区" >
          <el-col :span="7">
            <el-input v-model="coach.province" auto-complete="off" :rows="2" />
            <!-- <el-select v-model="coach.levelId" value-key="id">
              <el-option v-for="item in levelArray"  :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select> -->
          </el-col>
        </el-form-item>
        <el-form-item label="单位" >
          <el-col :span="7">
            <el-input v-model="coach.unit" auto-complete="off" :rows="2" />
          </el-col>
        </el-form-item>
          <el-form-item label="状态" >
            <el-col :span="7">
              <el-select v-model="coach.stateId" value-key="id">
                <el-option v-for="item in stateArray"  :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormAdd = false">取 消</el-button>
        <el-button type="primary" @click="add(coach)">确 定</el-button>
      </div>
    </el-dialog>
    </el-card>
  </div>
  </template>
  
  <script>
  import { mapState } from 'vuex'
  import searchTable from '@/components/PublicTable/index.vue'
  import {getCoachList, batchDelete, insert, getById, update} from "@/api/coach";
  import { Message} from "element-ui";
  // import {getLevelList} from "@/api/level";
  // import {getList} from "@/api/state";
  // import {getUserList} from "@/api/user";
  
  export default{
    components:{
      searchTable
    },
    data () {
      return {
        tableData: [],
        loading: false,
        tableRef: 'tableRef',
        searchForm: {},
        currentPage: 1,
        pageSizes: [10, 20, 50],
        pageSize: 10,
        total: 0,
        selectionList:[], //定义删除/批量删除
        dialogFormAdd:false,
        dialogFormEdit: false,
        coach:{
          id:'',
          name:'',
          sex:'',
          // levelId:'',
          province:'',
          note:'',
          stateId:'',
          state:'',
          unit:'',
          tel:'',
          userId:'',
          idCard:'',
          teamId:''
        },
        sexArry:[
          {
            "id": 1,
            "name": "男"
          },
          {
            "id": 2,
            "name": "女"
          }
        ],
        levelArray:[],
        stateArray:[
          {
            "id": 1,
            "name": "显示"
          },
          {
            "id": 2,
            "name": "隐藏"
          }
        ],
      rules:{
        name:[
          {
            required:true,message:'请填写姓名', trigger: 'blur'
          },
          {
            validator: function(rule, value, callback) {
              let name = /^[\u4E00-\u9FA5]{2,10}(·[\u4E00-\u9FA5]{2,10}){0,2}$/
              if (!name.test(value)) {
                callback(
                  new Error('请输入汉字(2-10)位')
                )
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        sex:[
          {
            required: true, message: '请选择性别', trigger: 'change'
          }
        ],
        tel:[
          {
            required:true,message:'请填写电话', trigger: 'blur'
          },
          {
            validator: function(rule, value, callback) {
              let phone = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/
              if (!phone.test(value)) {
                callback(
                  new Error('请输入正确手机号')
                )
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        idCard:[
        {
            required:true,message:'请填写身份证号', trigger: 'blur'
          },
          {
            validator: function(rule, value, callback) {
              let card = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
              if (!card.test(value)) {
                callback(
                  new Error('请输入正确身份证号')
                )
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
      };
    },
    created() {
      this.query()
      this.getTeamId()
    },
    computed:{
      ...mapState({
        user:state => state.user.userInfo
      })
    },
    methods: {
      getTeamId() {
        this.coach.teamId = this.user.teamId
      },
      query() {
        // 请求表格数据
        var params ={
          'pageNum': this.currentPage,
          'pageSize': this.pageSize,
          'name':this.searchForm.name,
          'tel':this.searchForm.tel,
          'sex':this.searchForm.sex
        }
        getCoachList(params).then(res => {
          // 把请求到的数据给testDatas数组
          this.tableData = res.data.list
          // 当前页数
          this.currentPage = res.data.currPage
          // 当前页数量
          this.pageSize = res.data.pageSize
          // 分页总数
          this.total = res.data.totalCount
          //   console.log(JSON.stringify(res.data.data.total))
        })
        .catch((error) => {
          console.log(error)
        })
      },
      doReset() {
        // 重置搜索条件
        // 请求表格数据
        this.tableData = [];
        this.restForm();
        this.query();
      },
      restForm(){
        this.searchForm.name = ""
        this.searchForm.tel = ""
        this.searchForm.sex = ""
      },
      selectionChange(val) {
        this.selectionList = []
        val.forEach(element => {
          this.selectionList.push(element.id)
        });
      },
      handlerDelete(){
        // 数组转字符串使用逗号分隔
        let ids =  this.selectionList.join(",")
        console.log(ids)
        var params ={
            'ids': ids
        }
        batchDelete(params).then(res =>{
          Message({
            message: '批量删除成功',
            type: 'success',
            duration: 3 * 1000
          })
          // 重新查询表格
          this.query()
        }).catch((error) => {
          console.log(error)
        })
      },
      handleSizeChange(val) {
        // 改变每页条数
        this.pageSize = val
        this.query()
      },
      handleCurrentChange(val) {
        // 切换页码
        this.currentPage = val
        this.query()
      },
      // table 数据转换
      formatSexType(row, column){
        if(row.sex === '1'){
            return '男'
        } else if(row.sex === '2') {
            return '女'
        } else {
            return ''
        }
      },
      // 新增教练
      addCoach(){
        this.coach = {}
        this.coach.teamId = this.user.teamId
        this.dialogFormAdd = true
      },
      // 修改教练
      editCoach(){
        // console.log('下标', index)
        // console.log('数据', row)
        console.log(this.selectionList)
        console.log(typeof(this.selectionList))
        let id = this.selectionList[0]
          var params = {
            'id' : id
          }
        getById(params).then(res =>{
          this.coach = {}
          this.coach = res.data
          this.dialogFormEdit = true
        }).catch((error) => {
            console.log(error)
        })
      },
      add(coach){
        this.$refs.coach.validate(valid => {
        if(valid) {
            insert(coach).then(res =>{
              Message({
                message: '教练新增成功',
                type: 'success',
                duration: 3 * 1000
              })
              // 新增弹出框隐藏
              this.dialogFormAdd = false
              // 重新查询表格
              this.query()
            }).catch((error) => {
              console.log(error)
            })
          } else {
            console.log('fail')
          }
        })
      },
      edit(coach){
        this.$refs.coach.validate(valid => {
          if(valid) {
            update(coach).then(res =>{
              Message({
                message: '教练修改成功',
                type: 'success',
                duration: 3 * 1000
              })
              // 新增弹出框隐藏
              this.dialogFormEdit = false
              // 重新查询表格
              this.query()
            }).catch((error) => {
              console.log(error)
            })
          } else {
            console.log('fail')
          }
        })
      }
    }
  }
  </script>
  <style>
  .info-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
  }
  </style>